import 'package:flutter/material.dart' hide MenuController;
import 'package:flutter_soundmagus/model/model.dart';
import 'package:flutter_soundmagus/page/eq/eq_controller.dart';
import 'package:flutter_soundmagus/page/eq/widget.dart';
import 'package:flutter_soundmagus/page/inout/widget/output_graph.dart';
import 'package:flutter_soundmagus/util/util.dart';
import 'package:flutter_soundmagus/widget/eq/DrawFunction.dart';
import 'package:flutter_soundmagus/widget/eq/EqView.dart';
import 'package:flutter_soundmagus/widget/eq/eq_wdiget.dart';
import 'package:flutter_soundmagus/widget/page_base.dart';
import 'package:flutter_soundmagus/widget/widget.dart';
import 'package:get/get.dart';
import 'package:keyboard_actions/keyboard_actions.dart';

import '../inout/summing_controller.dart';
import '../menu/menu_controller.dart';

class PageEq extends PageBase {
  const PageEq({Key? key}) : super(key: key);

  @override
  _PageEqState createState() => _PageEqState();
}

class _PageEqState extends PageBaseState with MsgParserRefreshMixin {
  @override
  bool get menuHidden => false;

  EqWidgetController eqWidgetController = EqWidgetController(0);

  EqView get eqView => eqWidgetController.eqView;

  final controller = Get.find<EqController>();

  EQModel? get model => controller.eqModel;
  EQItemModel? get itemModel => model!.getCurrentItemModel();

  XoverModel get xoverModel => DataMng().xoverModel;

  @override
  void initState() {
    super.initState();

    // WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
    //   updateEq(onDone: () {});
    //   setState(() {});
    // });

    Future.delayed(Duration(seconds: 1), () {
      updateEq(onDone: () {});
      setState(() {});
    });

    //监听db、freq、q的变化
    everAll([controller.db, controller.freq, controller.q, controller.selectCH],
        (v) {
      updateEq(onDone: () {});
    });

    Get.find<MenuController>().index.listen((p0) {
      Future.delayed(Duration(seconds: 1), () => {
        setState(() {})
        });
    });

    observeRefresh();
  }

  @override
  void refreshState(bool needSendData) {
    super.refreshState(needSendData);
    updateEq();
    if (mounted) {
      setState(() {});
    }
  }

  void updateEq({VoidCallback? onDone}) {
    if (!mounted || model == null) {
      return;
    }
    var eqmodel = model!, selectCH = eqmodel.chConfig.selectCh;
    var items = eqmodel.getItemsModel(selectCH),
        q = items.map((e) => e.q.toDouble()).toList(),
        eq = items.map((e) => e.ch.toDouble()).toList(),
        freq = items.map((e) => e.freq.toDouble()).toList();
    //EQ曲线
    eqView.setPEQ(q, eq, freq,
        width: MediaQuery.of(context).size.width.toInt());

    //xover
    if (eqmodel.chConfig.isChGrouped(ch: selectCH)) {
      eqView.setColor(0);
    } else {
      eqView.setColor(selectCH);
    }

    var cModel = xoverModel.itemModel();
    var high = DrawFunction.getOctType(cModel, true),
        low = DrawFunction.getOctType(cModel, false);
    eqView.setXover([cModel.low.freq.toDouble(), cModel.high.freq.toDouble()],
        [low.toDouble(), high.toDouble()]);

    // eqView.reArray();
    // eqView.refreshXover2(0);
    // eqView.refreshPEQ1(0);
    eqView.reXover();
    // eqView.refreshXover2(0);

    eqWidgetController.update();

    onDone?.call();
  }

  Widget _buildEq(BuildContext context) {
    return Obx(() => EqWidget(
          // pd: controller.pd.value,
          pdCount: controller.pdCount.value,
          controller: eqWidgetController,
          onPressPd: (pd) {
            controller.updatePd(pd);
          },
        ));
  }

  @override
  Widget buildBody(BuildContext context) {
    print('build eqview');
    Widget child = Column(
      // mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Container(
          padding: EdgeInsets.only(top: 20.w, left: 60.w, right: 60.w),
          height: 90,
          child: _buildEq(context), //曲线图
        ),
        SizedBox(
          height: Get.height - 90 - 40,
          width: Get.width,
          child: Stack(children: [
            Padding(
              padding: const EdgeInsets.only(left: 40),
              child: Row(
                children: [
                  Expanded(
                    child: Column(
                      children: [
                        Expanded(
                          child: PageView.builder(
                            controller: controller.pageController,
                            itemBuilder: (context, index) {
                              return Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: List.generate(index != 3 ? 8 : 7,
                                    (i) => EqItem(index * 8 + i)),
                              );
                            },
                            onPageChanged: (value) =>
                                controller.page.value = value,
                            itemCount: (EQModel.freqs.length / 8).ceil(),
                          ),
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            ImgBtn(
                              'arrow_left',
                              onTap: controller.prevPage,
                            ),
                            ...List.generate(
                                (EQModel.freqs.length / 8).ceil(),
                                (index) => Obx(() => Container(
                                      decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(5),
                                        color: controller.page.value == index
                                            ? Theme.of(context).primaryColor
                                            : Colors.white,
                                      ),
                                      width: 10,
                                      height: 10,
                                      margin:
                                          EdgeInsets.symmetric(horizontal: 10),
                                    ))),
                            ImgBtn(
                              'arrow_right',
                              onTap: controller.nextPage,
                            ),
                          ],
                        )
                      ],
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.symmetric(horizontal: 20),
                    width: 200.w,
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                        EqQFreqItem(
                          isQ: true,
                          focusNode: focusNodeQ,
                        ),
                        EqQFreqItem(
                          focusNode: focusNodeFreq,
                        ),
                      ],
                    ),
                  ),
                  SizedBox(
                    child: Obx(() => OutputGraph(
                          mini: true &&
                              Get.find<SummingController>().v.value >= 0,
                          miniScale: 0.65,
                          mode: Get.find<SummingController>()
                              .outputModeLast
                              .value,
                          leftDrive:
                              Get.find<SummingController>().leftDrive.value,
                          selecteds:
                              controller.chSelects.map((e) => e.value).toList(),
                          onChanged: (v) {
                            controller.updateSelectCh(v);
                            setState(() {});
                          },
                        )),
                    width: 220,
                    height: 220,
                  ),
                ],
              ),
            ),
            Obx(() => Visibility(
                visible: controller.bottomSelects[4].value, //禁止操作效果，盖一层半透明在顶部
                child: Container(
                  color: Colors.black.withOpacity(0.5),
                )))
          ]),
        ),
      ],
    );
    child = Column(
      children: [
        Expanded(
          child: KeyboardActions(
            //包住需要滚动的部分，不需要滚动上移的扔出外面
            config: _buildConfig(context),
            child: child,
          ),
        ),
        EqNav(),
      ],
    );
    // 模拟分享数据
    // child = Stack(
    //   children: [
    //     child,
    //     TextButton(
    //         onPressed: () {
    //           controller.eqModel.toCmdStr();
    //         },
    //         child: Container(
    //           alignment: Alignment.center,
    //           child: Text('mock'),
    //           width: 200,
    //           height: 44,
    //           color: Colors.white,
    //         ))
    //   ],
    // );
    return child;
  }

  final focusNode = FocusNode(),
      focusNodeFreq = FocusNode(),
      focusNodeQ = FocusNode();

  KeyboardActionsConfig _buildConfig(BuildContext context) {
    return KeyboardActionsConfig(
      keyboardActionsPlatform: KeyboardActionsPlatform.ALL,
      keyboardBarColor: Colors.grey,
      nextFocus: false,
      actions: [
        KeyboardActionsItem(
            focusNode: focusNodeFreq, onTapAction: controller.freqChange),
        KeyboardActionsItem(
            focusNode: focusNodeQ, onTapAction: controller.qChange),
      ],
    );
  }
}
